<script setup>
	// 定义渲染数据结构
	import { Modal } from 'ant-design-vue'
	import { designStore } from '@/views/plugin/dashboard/store'
	import tool from '@/utils/tool'
	import { CopyOutlined, DatabaseOutlined, DeleteOutlined, SettingOutlined } from '@ant-design/icons-vue'
	import { cloneDeep } from 'lodash-es'

	const useDesignStore = designStore()
	// 点击组件
	// const clickGridItem = (item) => {
	// 	useDesignStore.selectedComponent = cloneDeep(item)
	// }
	// 更新画布
	const onLayoutUpdated = (newLayout) => {
		useDesignStore.canvasSourceData = newLayout
		window.json = newLayout
	}
	// 点击画布空白处
	const gridLayoutClick = () => {
		useDesignStore.drawerStatus = 0
		useDesignStore.selectedComponent = {}
	}
	//  复制组件
	const handleCopy = (item) => {
		const site = item.x + item.w < 12
		// if(item.x + item.w < 12) {
		// 	const itemCopy = cloneDeep({ ...item, x: item.x + item.w, y: item.y, i: tool.snowyUuid() })
		// }else{
		// 	const itemCopy = cloneDeep({ ...item, x: 0, y: item.y + item.h, i: tool.snowyUuid() })
		// }
		const itemCopy = cloneDeep({
			...item,
			x: site ? item.x + item.w : 0,
			y: site ? item.y : item.y + item.h,
			i: tool.snowyUuid()
		})
		console.log(itemCopy)
		const index = useDesignStore.canvasSourceData.findIndex((d) => d.i === item.i)
		useDesignStore.canvasSourceData.splice(index + 1, 0, itemCopy)
	}
	// 拖拽结束
	const drop = (e) => {
		// 检查拖拽目标是否为布局组件内部
		const target = e.target
		const layoutContainer = target.closest(
			'.tab-drop-container, .grid-drop-container, .flex-drop-container, .card-drop-container, .split-drop-container'
		)

		// 如果拖拽到布局组件内部，不在主画布添加组件
		if (layoutContainer) {
			console.log('拖拽到布局组件内部，由布局组件处理')
			return
		}

		// 如果没有拖拽项，不处理
		if (!useDesignStore.activeDragAddItem) {
			console.log('没有拖拽项，不处理拖拽')
			return
		}

		// 计算拖拽位置相对于画布的坐标
		const gridLayout = e.currentTarget
		const rect = gridLayout.getBoundingClientRect()
		const offsetX = e.clientX - rect.left
		const offsetY = e.clientY - rect.top

		// 根据网格尺寸计算x和y的位置
		const colWidth = rect.width / 12 // 12列网格
		const rowHeight = 30 // 行高30px

		const x = Math.floor(offsetX / colWidth)
		const y = Math.floor(offsetY / rowHeight)

		// 创建新组件并添加到画布
		const item = cloneDeep({
			x: Math.min(Math.max(x, 0), 11), // 确保x在0-11之间
			y: Math.max(y, 0), // 确保y不小于0
			i: tool.snowyUuid(),
			...useDesignStore.activeDragAddItem
		})

		useDesignStore.canvasSourceData.push(item)
	}
	// 去除拖拽默认事件
	const dragleave = (e) => {
		e.preventDefault()
	}
	// 去除拖拽默认事件
	const dragover = (e) => {
		e.preventDefault()
	}
	// 删除画布上的组件
	const handleDelete = (item) => {
		Modal.confirm({
			title: '删除',
			content: '确认删除该组件',
			okText: '确认',
			cancelText: '取消',
			onOk: () => {
				const index = useDesignStore.canvasSourceData.findIndex((d) => d.i === item.i)
				useDesignStore.canvasSourceData.splice(index, 1)
				gridLayoutClick()
			}
		})
	}
	const handleResize = (item) => {}

	// 数据配置组件引用
	const refMap = {}
	const setRefMap = (el, item) => {
		if (el) {
			refMap[`${item.i}`] = el
		}
	}

	// 样式配置组件引用
	const styleConfigRef = ref(null)

	// 打开样式配置
	const openStyleConfig = (item) => {
		useDesignStore.selectedComponent = cloneDeep(item)
		useDesignStore.drawerStatus = 1
		useDesignStore.selectedComponentRef = refMap[item.i]
	}
	// 打开数据配置
	const openDataConfig = (item) => {
		useDesignStore.selectedComponent = cloneDeep(item)
		useDesignStore.drawerStatus = 2
		useDesignStore.selectedComponentRef = refMap[item.i]
	}
	// 修改选中的数据
	const upDataConfig = (value) => {
		useDesignStore.selectedComponent = value
		const actived = useDesignStore.selectedComponent || {}
		const index = useDesignStore.canvasSourceData.findIndex((d) => d.i === actived.i)
		useDesignStore.canvasSourceData.splice(index, 1, value)
	}
	// 调用定时任务
	const onReload = () => {
		// 遍历画布上的所有组件
		useDesignStore.canvasSourceData.forEach((item) => {
			// 获取对应组件的ref引用
			const componentRef = refMap[item.i]
			// 如果组件存在且有reload方法，则调用
			if (componentRef && typeof componentRef.onReload === 'function') {
				componentRef.onReload()
			}
		})
	}
	defineExpose({
		onReload
	})
</script>

<template>
	<GridLayout
		@drop="drop"
		@dragleave="dragleave"
		@dragover="dragover"
		v-model:layout="useDesignStore.canvasSourceData"
		:col-num="12"
		:row-height="30"
		:is-draggable="useDesignStore.mode === 'design'"
		:is-resizable="useDesignStore.mode === 'design'"
		vertical-compact
		use-css-transforms
		@layout-updated="onLayoutUpdated"
		class="wrapper h-[100%] min-h-[100%] min-w-[100%]"
	>
		<div class="draw" @click="gridLayoutClick"></div>
		<GridItem
			v-for="item in useDesignStore.canvasSourceData"
			:key="item.i"
			:x="item.x"
			:y="item.y"
			:w="item.w"
			:h="item.h"
			:i="item.i"
			:static="useDesignStore.mode === 'show'"
			:id="'box' + item.i"
			@resize="handleResize"
			:style="{ 'border-color': `${item.i === useDesignStore.selectedComponent.i ? '#45a5ffcc' : 'transparent'}` }"
			class="item relative"
		>
			<component
				:is="item.name"
				:id="item.i"
				:config="item"
				:key="item.i"
				:ref="(el) => setRefMap(el, item)"
				@upDataConfig="upDataConfig"
			/>
			<div v-if="useDesignStore.mode === 'design'" class="action absolute right-[10px] top-[10px]">
				<a-tooltip placement="bottom">
					<template #title>
						<span>样式</span>
					</template>
					<a-button @click="openStyleConfig(item)" size="small" style="margin-right: 5px">
						<SettingOutlined />
					</a-button>
				</a-tooltip>
				<a-tooltip placement="bottom">
					<template #title>
						<span>数据</span>
					</template>
					<a-button @click="openDataConfig(item)" size="small" style="margin-right: 5px">
						<DatabaseOutlined />
					</a-button>
				</a-tooltip>
				<a-tooltip placement="bottom">
					<template #title>
						<span>复制</span>
					</template>
					<a-button @click="handleCopy(item)" size="small" style="margin-right: 5px">
						<CopyOutlined />
					</a-button>
				</a-tooltip>
				<a-tooltip placement="bottom">
					<template #title>
						<span>删除</span>
					</template>
					<a-button @click="handleDelete(item)" size="small">
						<DeleteOutlined />
					</a-button>
				</a-tooltip>
			</div>
		</GridItem>
	</GridLayout>
</template>

<style scoped lang="less">
	.action {
		display: none;
	}

	.item {
		border: 1px solid transparent;
		border-radius: 2px;
	}

	.item:hover .action {
		display: block;
	}

	.draw {
		height: 100%;
		position: absolute;
		width: 100%;
		top: 0px;
		left: 0px;
	}
</style>
